<template>
  <div class="app-tab h-44" :class="{ 'single-tab': tabs.length <= 1 }">
    <vue3-tabs-chrome
      ref="tabRef"
      @click="onTabClick"
      @close="onTabClose"
      class="h-full"
      :tabs="tabs"
      v-model="tab"
    />
  </div>
</template>

<script lang="ts" setup>
import Vue3TabsChrome from "vue3-tabs-chrome";
import "vue3-tabs-chrome/dist/vue3-tabs-chrome.css";
import { ref } from "vue";
import { AppTab, useAppStore } from "@/store";

const route = useRoute();
const router = useRouter();
const appStore = useAppStore();

const tabRef = ref();
const tabs = ref<AppTab[]>(
  appStore.tabs.map((item) => {
    return {
      name: item.name,
      label: item.label,
      key: item.key,
      icon: item.icon,
      favico: () => h("i", { class: item.icon }),
    };
  }),
);
const tab = ref<string>();
const onActiveTab = (path: string) => {
  const target = tabs.value.find((t) => t.key == path);
  if (target) {
  } else {
    tabRef.value.addTab({
      label: route.meta?.title!,
      key: route.path,
      icon: route.meta?.icon,
      favico: () => h("i", { class: route.meta?.icon }),
      name: route.name,
    });
  }

  refreshTabs();
  tab.value = path;
  appStore.setCurrentTab(tab.value);
};

const refreshTabs = () => {
  appStore.setTabs(
    tabs.value.map((item) => {
      return {
        name: item.name,
        label: item.label,
        key: item.key,
        icon: item.icon,
      };
    }),
  );
};

const onTabClick = (_, v: AppTab) => {
  onActiveTab(v.key);
  router.push(v.key);
};

const onTabClose = () => {
  nextTick(() => {
    refreshTabs();
    if (appStore.currentTab != tab.value) {
      onActiveTab(tab.value!);
      router.push(tab.value!);
    }
  });
};

watch(route, (to) => {
  onActiveTab(to.path);
});

onMounted(() => {
  onActiveTab(route.path);
});
</script>

<style lang="scss">
.app-tab {
  &.single-tab {
    .tabs-close {
      display: none;
    }
  }
  .vue3-tabs-chrome {
    padding-top: 0;
    background-color: var(--el-bg-color-page);
    .tabs-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
    .tabs-close {
      font-size: 0;
    }
    .tabs-content {
      height: 44px;

      .tabs-item:not(.active):hover {
        .tabs-background-content {
          background-color: #eaebec;
        }
        .tabs-background-before,
        .tabs-background-after {
          fill: #eaebec;
        }
      }

      .tabs-item:first-child {
        .tabs-background {
          padding-left: 0;
          .tabs-background-content {
            border-top-left-radius: 0;
          }
        }
      }

      .tabs-item.active {
        .tabs-label {
          color: var(--el-text-color-primary);
        }
        .tabs-background-content {
          box-shadow:
            0px 6px 18px 6px rgba(31, 35, 41, 0.03),
            0px 3px 6px -6px rgba(31, 35, 41, 0.05),
            0px 4px 8px 0px rgba(31, 35, 41, 0.03);
        }
      }
    }
  }
}
</style>
